Welcome to django!

7.09 新增图书

1、新增urls:

urlpatterns=[

path("list",views.book_list,name="book_list"),

path("create",views.book_create),

]


2、新增create.html文件

{% extends "index.html" %}

{% block content %}

<h1 class="text-center"> 添加页面 </h1 >

<form action="/book/create" method="post">

{% csrf_token %}

<!--Forbidden (403)-- >

< p>

书名:

<input type="text" name="title" class="form-control" >

</p>

<p>

价格:

<input type="text" name="price" class="form-control" >

</p>

<p>

出版日期:

<input type="date" name="publish_date" class="form-control" >

</p>

<p>

出版社:

<select name="publisher" class="form-control">

{% for p in publisher %}

<option value="{{ p }}">{{ p }}< /option>

{% endfor %}

</select>

</p>

<p>

作者:

<select name="authors" multiple class="form-control" >

{% for p in authors %}

<option value="{{ p }}">{{ p }} < /option >

{% endfor %}

</select>

</p>

<input type="submit" value="新增" class="btn btn-primary btn-block">

</form>

{% endblock %}


3、 新增views:

def book_create(request):

if request.method =="GET":

publisher=["北京出版社","南京出版社","上海出版社"]

authors = ["李白", "杜甫", "笑笑生","李时珍","欧阳修"]

return render(

request,

template_name="create.html",

context={"publisher":publisher,"authors":authors}

)

# post

conn = pymysql.connect(

host="127.0.0.1",

port=3306,

user="root",

password="502",

db="bms",

charset="utf8",

cursorclass=pymysql.cursors.DictCursor

)

data=request.POST

with conn.cursor() as cursor:

sql="insert book (title,price,publish_date,publisher,authors) VALUES(%s,%s,%s,%s,%s)"

book_data=(

data.get("title"),

data.get("price"),

data.get("publish_date"),

data.get("publisher"),

"".join(data.getlist("authors"))

)

cursor.execute(sql,book_data)

conn.commit()

return redirect(to="/book/list")